package com.example.element.module.content_provider

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.provider.ContactsContract
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.common.base.AbsActivity
import com.example.element.R
import com.example.element.databinding.ActProviderContactsBinding
import com.example.element.module.content_provider.adapter.ContactsListAdapter
import com.example.element.module.content_provider.bean.ContactBean
import kotlinx.android.synthetic.main.act_provider_contacts.*

class ContactsActivity : AbsActivity<ActProviderContactsBinding>() {

    //读取联系人权限
    private val permission = Manifest.permission.READ_CONTACTS
    private val data = ArrayList<ContactBean>()
    //延时初始化 lateinit
    private lateinit var mAdapter: ContactsListAdapter

    companion object{
        @JvmStatic
        fun open(context:Context) {
            context.startActivity(Intent(context,ContactsActivity::class.java))
        }
    }

    override fun getLayoutId() = R.layout.act_provider_contacts

    override fun main() {
        //init RecyclerView
        mAdapter = ContactsListAdapter(data)
        rv.layoutManager = LinearLayoutManager(mContext)
        rv.adapter = mAdapter
        //判断权限
        if (ContextCompat.checkSelfPermission(mContext, permission) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(permission), 100)
        } else {
            getContacts()
        }
    }

    /**
     * 查询联系人
     */
    private fun getContacts() {
        contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null)?.apply {
            while (moveToNext()) {
                val name = getString(getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))
                val number = getString(getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
                data.add(ContactBean(name, number))
            }
            mAdapter.notifyDataSetChanged()
            close()
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            100 -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    getContacts()
                } else {
                    Toast.makeText(mContext, "You denied the permission", Toast.LENGTH_SHORT).show()
                }

            }
        }
    }

    override fun initListener() {
    }
}